package cn.dapeng.features;

import cn.dapeng.util.SleepingUtil;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;


/**
 * synchronized 与ReentrantLock具有同样的作用
 */
public class ReentrantLock_T01 {


    public synchronized static void m1() {
        for (int i = 0; i < 10; i++) {
            SleepingUtil.sleep(1, TimeUnit.SECONDS);
            System.out.println(Thread.currentThread().getName() + " : " + i);

            if (i == 2) {
                m2();
            }
        }
    }

    public synchronized static void m2() {
        System.out.println(Thread.currentThread().getName() + " running!");
    }

    // ************************************

    static ReentrantLock lock = new ReentrantLock();

    public static void k1() {
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                SleepingUtil.sleep(1, TimeUnit.SECONDS);
                System.out.println(Thread.currentThread().getName() + " : " + i);
            }

        } finally {
            lock.unlock();
        }
    }

    public static void k2() {
        lock.lock();
        System.out.println(Thread.currentThread().getName() + " running!");
        lock.unlock();
    }

    public static void main(String[] args) throws Exception {

        // 第一组测试 使用synchronized作用
//        Thread t1 = new Thread(ReentrantLock_T01::m1, "t1");
//        t1.start();
//
//        SleepingUtil.sleep(1, TimeUnit.SECONDS);
//
//        Thread t2 = new Thread(ReentrantLock_T01::m2, "t2");
//        t2.start();
//
//        t1.join();
//        t2.join();

        // 第二组测试 使用ReentrantLock作用
        Thread k1 = new Thread(ReentrantLock_T01::k1, "k1");
        k1.start();
        SleepingUtil.sleep(1, TimeUnit.SECONDS);
        Thread k2 = new Thread(ReentrantLock_T01::k2, "k2");
        k2.start();


        k1.join();
        k2.join();

    }
}
